package ext.tianma.MaterialClassification;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import ext.com.core.CoreUtil;
import ext.com.iba.IBAUtil;
import ext.tianma.part.PartCommands;
import wt.enterprise.MadeFromLink;
import wt.fc.Identified;
import wt.fc.IdentityHelper;
import wt.fc.PersistenceHelper;
import wt.fc.PersistenceServerHelper;
import wt.fc.QueryResult;
import wt.part.WTPart;
import wt.part.WTPartMasterIdentity;
import wt.util.WTException;
import wt.util.WTProperties;
import wt.util.WTPropertyVetoException;

public class AVLPartCommandsUtils {

	public static boolean VERBOSE = true;

	/**
	 * 原材料编码
	 * 
	 * @param avlPart
	 * @throws WTException
	 * @throws IOException
	 * @throws WTPropertyVetoException
	 * @throws InvalidFormatException
	 * @throws NumberFormatException
	 */
	public static String generateRowMaterialNumber(WTPart avlPart,String eName)
			throws WTException, IOException, WTPropertyVetoException, InvalidFormatException, NumberFormatException {
		
		String number = "";
		String laftNumber = "";
		WTPart orgPart = null;
		Workbook we = null;
		InputStream in = null;
		String path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if (null == path || path.equals("")) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if (null == in || null == we) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}

		String softType = IBAUtil.getSoftType(avlPart).getLogicalIdentifier();
		softType = softType.substring(softType.lastIndexOf(".") + 1);

//		String eName = (String) IBAUtil.getIBAValue(avlPart, "partEName");
		if (null == eName || eName.equals("")) {
			throw new WTException("没有获取到原材料的英文名称，无法生成编码！");
		}
		String seqName = PartCommands.getSequenceName(we.getSheetAt(2), eName);
		if (null == seqName || seqName.equals("")) {
			throw new WTException("没有获取到对应的序列名称，请从检查英文名称在配置表中是否存在！");
		}
		if (VERBOSE) {
			System.out.println("Debug 生成原材料编码   物料英文名称：" + eName);
			System.out.println("Debug 生成原材料编码    获取到的序列名称：" + seqName);
			System.out.println("Debug 生成原材料编码   物料原始编号：" + avlPart.getNumber());
			System.out.println("Debug 生成原材料编码    物料的类型：" + softType);
		}
		WTPart exitPart;
		avlPart = PartCommands.getWTPartByNumViewAndVersion(avlPart.getNumber(), "Design", "0.0");
		QueryResult qr = PersistenceHelper.manager.navigate(avlPart, "original", MadeFromLink.class, false);
		if ((qr == null) || (qr.size() == 0)) {
			laftNumber = "0";
		} else {
			while (qr.hasMoreElements()) {
				MadeFromLink link = (MadeFromLink) qr.nextElement();

				orgPart = (WTPart) link.getOriginal();
			}
			String orgNumber = orgPart.getNumber();
			if ((orgNumber != null) && (!orgNumber.trim().isEmpty())) {
				laftNumber = orgNumber.substring(orgNumber.length() - 1);
			}
		}
		avlPart = CoreUtil.getWTPartByNumberAndView(avlPart.getNumber(), avlPart.getViewName());
		do {
			
			if (softType.equals("AVLMaterial")) {
				System.out.println("======>>>start into ");
				String bigClass = "1";

				String littleClass = PartCommands.getLitteClassCode(we.getSheetAt(0), eName);
				if (VERBOSE) {
					System.out.println("Debug 生成原材料编码    英文名称：" + eName);
					System.out.println("Debug 生成原材料编码   小类码：" + littleClass);
				}
				if ((littleClass == null) || (littleClass.equals(""))) {
					throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
				}

				String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
				if (VERBOSE) {
					System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
				}
				NumberFormat nf = NumberFormat.getInstance();
				nf.setMinimumIntegerDigits(6);
				nf.setMaximumIntegerDigits(6);
				nf.setGroupingUsed(false);
				waterCode = nf.format(Integer.parseInt(waterCode.trim()));

				number = bigClass + littleClass + waterCode + laftNumber;
				System.out.println("number====>>"+number);
				/**
				 * @author xuge_ning
				 * @reason:新增TopPolarizer和BotPolarizer物料类型，同属于偏光片。
				 */
			} else if (softType.equals("Polarizer") || softType.equals("TopPolarizer")
					|| softType.equals("BotPolarizer")) {
				String polarizerType = (String) IBAUtil.getIBAValue(avlPart, "partCName");
				System.out.println("Debug 生成原材料编码   偏光片的类型：" + polarizerType);
				if ((polarizerType != null) && (polarizerType.equals("偏光片TOP"))) {
					String bigClass = "1";

					String littleClass = PartCommands.getLitteClassCode(we.getSheetAt(0), eName);
					System.out.println("Debug 生成原材料编码    小类码：" + littleClass);
					if ((littleClass == null) || (littleClass.equals(""))) {
						throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
					}
					String waterCode = null;
					int count;
					do {
						waterCode = PersistenceHelper.manager.getNextSequence(seqName);
						System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
						count = Integer.parseInt(waterCode);
					} while (count % 2 != 1);

					NumberFormat nf = NumberFormat.getInstance();
					nf.setMinimumIntegerDigits(7);
					nf.setMaximumIntegerDigits(7);
					nf.setGroupingUsed(false);
					waterCode = nf.format(Integer.parseInt(waterCode.trim()));

					number = bigClass + littleClass + waterCode;
				} else if ((polarizerType != null) && (polarizerType.equals("偏光片BOTTOM"))) {
					String bigClass = "1";

					String littleClass = PartCommands.getLitteClassCode(we.getSheetAt(0), eName);
					System.out.println("Debug 生成原材料编码    小类码：" + littleClass);
					if ((littleClass == null) || (littleClass.equals(""))) {
						throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
					}
					String waterCode = null;
					int count;
					do {
						waterCode = PersistenceHelper.manager.getNextSequence(seqName);
						System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
						count = Integer.parseInt(waterCode);
					} while (count % 2 != 0);

					NumberFormat nf = NumberFormat.getInstance();
					nf.setMinimumIntegerDigits(6);
					nf.setMaximumIntegerDigits(6);
					nf.setGroupingUsed(false);
					waterCode = nf.format(Integer.parseInt(waterCode.trim()));

					number = bigClass + littleClass + waterCode + laftNumber;
				} else {
					String bigClass = "1";

					String littleClass = PartCommands.getLitteClassCode(we.getSheetAt(0), eName);
					System.out.println("Debug 生成原材料编码  小类码：" + littleClass);
					if ((littleClass == null) || (littleClass.equals(""))) {
						throw new WTException("没有获取到原材料的物料代码，无法生成编码！");
					}

					String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
					NumberFormat nf = NumberFormat.getInstance();
					nf.setMinimumIntegerDigits(6);
					nf.setMaximumIntegerDigits(6);
					nf.setGroupingUsed(false);
					waterCode = nf.format(Integer.parseInt(waterCode.trim()));

					number = bigClass + littleClass + waterCode + laftNumber;
				}
			} else if (softType.equals("PhantomPolarizer")) {
				String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
				NumberFormat nf = NumberFormat.getInstance();
				nf.setMinimumIntegerDigits(6);
				nf.setMaximumIntegerDigits(6);
				nf.setGroupingUsed(false);
				waterCode = nf.format(Integer.parseInt(waterCode.trim()));

				number = "POL" + waterCode + laftNumber;
			}

			exitPart = PartCommands.getWTPartByNumber(number);
		} while (exitPart != null);

		System.out.println("Debug 生成原材料编码   生成的物料号为：" + number);
		return number;
	}

	public static String generateRowAVLNumber(WTPart avlPart)
			throws WTException, IOException, WTPropertyVetoException, InvalidFormatException, NumberFormatException {
		String number = "";
		String partNumber = "";
		String laftNumber = "";
		WTPart orgPart = null;
		Workbook we = null;
		InputStream in = null;
		String path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if (null == path || path.equals("")) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if (null == in || null == we) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}

//		String softType = IBAUtil.getSoftType(avlPart).getLogicalIdentifier();
//		softType = softType.substring(softType.lastIndexOf(".") + 1);
		//获取分类
		String nodeFileName = CreatePartClassificationUtil.getClassification(avlPart);
//		String eName = (String) IBAUtil.getIBAValue(avlPart, "partEName");
		if (null == nodeFileName || nodeFileName.equals("")) {
			throw new WTException("没有获取到原材料的分类，无法生成编码！");
		}
		System.out.println("nodeFileName=====>>>"+nodeFileName);
		String seqName = PartCommands.getSequenceName(we.getSheetAt(3), nodeFileName);
		if (null == seqName || seqName.equals("")) {
			throw new WTException("没有获取到对应的序列名称，请从检查英文名称在配置表中是否存在！");
		}
		if (VERBOSE) {
			System.out.println("Debug 生成原材料编码   物料分类：" + nodeFileName);
			System.out.println("Debug 生成原材料编码    获取到的序列名称：" + seqName);
			System.out.println("Debug 生成原材料编码   物料原始编号：" + avlPart.getNumber());
//			System.out.println("Debug 生成原材料编码    物料的类型：" + softType);
		}
		avlPart = PartCommands.getWTPartByNumViewAndVersion(avlPart.getNumber(), "Design", "0.0");
		QueryResult qr = PersistenceHelper.manager.navigate(avlPart, "original", MadeFromLink.class, false);
		if ((qr == null) || (qr.size() == 0)) {
			System.out.println("===>>>into===");
			laftNumber = "0";
		} else {
			System.out.println("===>>>into2===");
			while (qr.hasMoreElements()) {
				MadeFromLink link = (MadeFromLink) qr.nextElement();

				orgPart = (WTPart) link.getOriginal();
			}
			String orgNumber = orgPart.getNumber();
			if ((orgNumber != null) && (!orgNumber.trim().isEmpty())) {
				laftNumber = orgNumber.substring(orgNumber.length() - 1);
			}
		}
		System.out.println("===into==="+laftNumber);
		avlPart = CoreUtil.getWTPartByNumberAndView(avlPart.getNumber(), avlPart.getViewName());
//		if (softType.equals("RawMaterial")) {

			String littleClass = getLitteClassCode(we.getSheetAt(3), nodeFileName);
			if (VERBOSE) {
				System.out.println("Debug 生成原材料编码    分类：" + nodeFileName);
				System.out.println("Debug 生成原材料编码   小类码：" + littleClass);
			}
			if ((littleClass == null) || (littleClass.equals(""))) {
				throw new WTException("没有获取到原材料的物料分类，无法生成编码！");
			}

			String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
			if (VERBOSE) {
				System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
			}
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumIntegerDigits(6);
			nf.setMaximumIntegerDigits(6);
			nf.setGroupingUsed(false);
			waterCode = nf.format(Integer.parseInt(waterCode.trim()));
			System.out.println("laftNumber=====>>>>"+laftNumber);
			partNumber = littleClass + waterCode;
			/**
			 * @author xuge_ning
			 * @reason:新增TopPolarizer和BotPolarizer物料类型，同属于偏光片。
			 */
//		} 

		System.out.println("Debug 生成原材料编码   生成的物料号为：" + partNumber);
//		Identified partidentified = (Identified) avlPart.getMaster();
//		WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified.getIdentificationObject();
//		partmasteridentity.setNumber(number);
//		partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
//		PersistenceServerHelper.manager.update(partidentified);
//		avlPart = (WTPart) PersistenceHelper.manager.refresh(avlPart);
//		System.out.println("Debug 生成原材料编码   生成的物料号为：" + avlPart.getNumber());
		return partNumber;
	}
	

	public static String generateRowXNNumber(WTPart avlPart,String eName)
			throws WTException, IOException, WTPropertyVetoException, InvalidFormatException, NumberFormatException {
		String number = "";
		String partNumber = "";
		String laftNumber = "";
		WTPart orgPart = null;
		Workbook we = null;
		InputStream in = null;
		String path = (WTProperties.getLocalProperties()).getProperty("ext.tianma.cfg.RawMaterialsAndClassCode");
		in = new FileInputStream(path);
		we = WorkbookFactory.create(in);
		if (null == path || path.equals("")) {
			throw new WTException("没有获取到原材料代码及类别的配置路径，请检查!");
		}
		if (null == in || null == we) {
			throw new WTException("没有获取到原材料代码及类别的配置文件，请检查");
		}

//		String softType = IBAUtil.getSoftType(avlPart).getLogicalIdentifier();
//		softType = softType.substring(softType.lastIndexOf(".") + 1);
		//获取分类
//		String nodeFileName = CreatePartClassificationUtil.getClassification(avlPart);
////		String eName = (String) IBAUtil.getIBAValue(avlPart, "partEName");
//		if (null == nodeFileName || nodeFileName.equals("")) {
//			throw new WTException("没有获取到原材料的分类，无法生成编码！");
//		}
		System.out.println("nodeFileName=====>>>"+eName);
		String seqName = PartCommands.getSequenceName(we.getSheetAt(2), eName);
		if (null == seqName || seqName.equals("")) {
			throw new WTException("没有获取到对应的序列名称，请从检查英文名称在配置表中是否存在！");
		}
		if (VERBOSE) {
			System.out.println("Debug 生成原材料编码   物料分类：" + eName);
			System.out.println("Debug 生成原材料编码    获取到的序列名称：" + seqName);
			System.out.println("Debug 生成原材料编码   物料原始编号：" + avlPart.getNumber());
//			System.out.println("Debug 生成原材料编码    物料的类型：" + softType);
		}
		avlPart = PartCommands.getWTPartByNumViewAndVersion(avlPart.getNumber(), "Design", "0.0");
		QueryResult qr = PersistenceHelper.manager.navigate(avlPart, "original", MadeFromLink.class, false);
		if ((qr == null) || (qr.size() == 0)) {
			System.out.println("===>>>into===");
			laftNumber = "0";
		} else {
			System.out.println("===>>>into2===");
			while (qr.hasMoreElements()) {
				MadeFromLink link = (MadeFromLink) qr.nextElement();

				orgPart = (WTPart) link.getOriginal();
			}
			String orgNumber = orgPart.getNumber();
			if ((orgNumber != null) && (!orgNumber.trim().isEmpty())) {
				laftNumber = orgNumber.substring(orgNumber.length() - 1);
			}
		}
		System.out.println("===into==="+laftNumber);
		avlPart = CoreUtil.getWTPartByNumberAndView(avlPart.getNumber(), avlPart.getViewName());
//		if (softType.equals("RawMaterial")) {

			String littleClass = getLitteClassCode(we.getSheetAt(2), eName);
			if (VERBOSE) {
				System.out.println("Debug 生成原材料编码    分类：" + eName);
				System.out.println("Debug 生成原材料编码   小类码：" + littleClass);
			}
			if ((littleClass == null) || (littleClass.equals(""))) {
				throw new WTException("没有获取到原材料的物料分类，无法生成编码！");
			}

			String waterCode = PersistenceHelper.manager.getNextSequence(seqName);
			if (VERBOSE) {
				System.out.println("Debug 生成原材料编码    获取到的序列为：" + waterCode);
			}
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumIntegerDigits(6);
			nf.setMaximumIntegerDigits(6);
			nf.setGroupingUsed(false);
			waterCode = nf.format(Integer.parseInt(waterCode.trim()));
			System.out.println("laftNumber=====>>>>"+laftNumber);
			partNumber = littleClass + waterCode;
			/**
			 * @author xuge_ning
			 * @reason:新增TopPolarizer和BotPolarizer物料类型，同属于偏光片。
			 */
//		} 

		System.out.println("Debug 生成原材料编码   生成的物料号为：" + partNumber);
//		Identified partidentified = (Identified) avlPart.getMaster();
//		WTPartMasterIdentity partmasteridentity = (WTPartMasterIdentity) partidentified.getIdentificationObject();
//		partmasteridentity.setNumber(number);
//		partidentified = IdentityHelper.service.changeIdentity(partidentified, partmasteridentity); // 更新名称
//		PersistenceServerHelper.manager.update(partidentified);
//		avlPart = (WTPart) PersistenceHelper.manager.refresh(avlPart);
//		System.out.println("Debug 生成原材料编码   生成的物料号为：" + avlPart.getNumber());
		return partNumber;
	}
	
	/**
	 * 获取物料代码
	 * 
	 * @param sheet sheet对象
	 * @param EName 英文名称
	 * @return 物料代码
	 * @throws WTException
	 */
	public static String getLitteClassCode(Sheet sheet, String EName) throws WTException {
		String code = null;
		for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
			Row row = sheet.getRow(i);
			String temp = PartCommands.getCellValue(row.getCell(2)).trim();
			System.out.println("temp=====>>"+temp);
			if (null == temp || temp.equals("")) {
				continue;
			} else {
				if (temp.equals(EName)) {
					code = PartCommands.getCellValue(row.getCell(0));

				}
			}
		}
		return code;
	}

}
